package cn.dansj.common.utils.jdbc;

import cn.dansj.common.utils.transfer.Transformation;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

@SuppressWarnings("SqlSourceToSinkFlow")
public class JdbcUtils {
    private final NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    public JdbcUtils(JdbcTemplate jdbcTemplate) {
        this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate);
    }

    public int insert(String table, Map<String, Object> data, boolean decamelize) {
        StringBuilder columnBuilder = new StringBuilder();
        StringBuilder paramsBuilder = new StringBuilder();
        for (String key : data.keySet()) {
            paramsBuilder.append(":").append(key).append(",");
            columnBuilder.append(decamelize ? Transformation.decamelize(key, "_") : key).append(",");
        }
        String insert = "insert into " + table + "(" + columnBuilder.substring(0, columnBuilder.toString().length() - 1) + ") values (" + paramsBuilder.substring(0, paramsBuilder.toString().length() - 1) + ")";
        return namedParameterJdbcTemplate.update(insert, data);
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    public int batchInsert(String table, List<Map<String, Object>> data, boolean decamelize) {
        StringBuilder columnBuilder = new StringBuilder();
        StringBuilder paramsBuilder = new StringBuilder();
        for (String key : data.get(0).keySet()) {
            paramsBuilder.append(":").append(key).append(",");
            columnBuilder.append(decamelize ? Transformation.decamelize(key, "_") : key).append(",");
        }
        String insert = "insert into " + table + "(" + columnBuilder.substring(0, columnBuilder.toString().length() - 1) + ") values (" + paramsBuilder.substring(0, paramsBuilder.toString().length() - 1) + ")";
        final Map[] maps = data.toArray(new Map[0]);

        return Arrays.stream(namedParameterJdbcTemplate.batchUpdate(insert, maps)).sum();
    }
}
